<template>
  <div class="formBd">
    <el-form :model="form" label-width="120px" ref="ruleForm" :rules="rules">
      <el-form-item label="产品图片" prop="productImages">
        <el-upload :file-list="form.productImages" list-type="picture-card" :on-success="handleProductImageSuccess"
          :on-error="handleProductImageError" :on-remove="handleRemoveProductImage"
          :before-upload="beforeProductImageUpload" :limit="5" class="upload-demo"  action="/api/upload" multiple>
          <i class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
      <img
        class="el-upload-list__item-thumbnail"
        :src="file.url" alt=""
      >
      <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
         @click.stop="moveImagePrev(file)"
        >
          <i class="el-icon-d-arrow-left"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
           @click.stop="moveImageNext(file)"
           
        >
          <i class="el-icon-d-arrow-right"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          
            @click.stop="handleRemoveProductImage(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
    </div>
          <!-- <div slot="file" slot-scope="{file}">
            <div class="image-actions">
              <img :src="file.url" class="el-upload-list__item-thumbnail" />
              <div class="action-buttons">
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click.stop="handleRemoveProductImage(file)">
                    <i class="el-icon-delete-solid"></i>
                  </span>
                  <span class="el-upload-list__item-move-prev" @click.stop="moveImagePrev(file)">
                    <i class="el-icon-d-arrow-left"></i>
                  </span>
                  <span class="el-upload-list__item-move-next" @click.stop="moveImageNext(file)">
                    <i class="el-icon-d-arrow-right"></i>
                  </span>
                </span>
              </div>
            </div>
          </div> -->
        </el-upload>
        <div class="upload-tip">可添加多张图片，大小限制10M以内</div>
      </el-form-item>
      <el-form-item label="产品名称" prop="title">
        <el-input class="inputWidth" v-model="form.title" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-select class="inputWidth" v-model="form.brand" placeholder="请选择">
          <el-option v-for="(option, index) in brandOptions" :key="index" :label="option.title"
            :value="option.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" class="inputWidth" controls-position="right" :min="1" ></el-input-number>
        <div class="sort-tip">数字越大越靠前</div>
      </el-form-item>
      <el-form-item label="类型" prop="productType">
        <el-select class="inputWidth" v-model="form.productType" placeholder="请选择产品分类">
          <el-option v-for="(option, index) in typeOptions" :key="index" :label="option.title"
            :value="option.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input class="priceWidth" v-model="form.price" placeholder="￥" type="number"></el-input>
      </el-form-item>
      <el-form-item label="介绍信息" prop="content">
        <div  class="inputWidth">
          <quill-editor v-model="form.content" :options="editorOption" class="quill-editor-custom"></quill-editor>
        </div>
      </el-form-item>
      <el-form-item label="证书及产品资料" prop="certificatesAndMaterials" required>
        <el-upload :file-list="form.certificatesAndMaterials" :on-success="handleCertificateSuccess"
          :on-error="handleCertificateError" :on-remove="handleRemoveCertificate"
          :before-upload="beforeCertificateUpload" :limit="5"  list-type="picture-card"  action="/api/upload" multiple>
          <i class="el-icon-plus"></i>
          <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
        </el-upload>

        <div class="upload-tip">可添加多张图片，大小限制10M以内</div>
      </el-form-item>
      <el-form-item>
        <el-button class="btnColse" @click="cancel">取消</el-button>
        <el-button class="btnPay" type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';

export default {
  name: "ReleaseProduct",
  components: {
    quillEditor
  },
  data() {
    return {
      form: {
        productImages: [],
        title: '',
        brand: '',
        productType: '',
        price: '',
        content: '',
        certificatesAndMaterials: [],
        sort:''
      },
      rules: {
        productImages: [{ required: true, message: '请上传产品图片', trigger: 'blur' }],
        title: [
          { required: true, message: '请输入公司名称', trigger: 'blur' }
        ],
        brand: [{ required: true, message: '请选择品牌', trigger: 'blur' }],
      },
      uploadUrl: '#', // 实际应用中替换为真实的上传地址
      brandOptions: [
      ],
      typeOptions: [
      ],
      editorOption: {
        theme: 'snow',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            [{ 'indent': '-1' }, { 'indent': '+1' }],
            [{ 'direction': 'rtl' }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['clean'],
            ['link', 'image', 'video']
          ]
        }
      }
    }
  },
  computed: {
    ...mapState([
      "userInfo",
    ]),
  },
  created() {
    this.getType();
    this.getBrandType();
  },
  methods: {
    moveImagePrev(file) {
    const index = this.form.productImages.findIndex(item => item.uid === file.uid);
    if (index > 0) {
      const temp = this.form.productImages[index];
      this.$set(this.form.productImages, index, this.form.productImages[index - 1]);
      this.$set(this.form.productImages, index - 1, temp);
    }
  },
  moveImageNext(file) {
    const index = this.form.productImages.findIndex(item => item.uid === file.uid);
    if (index < this.form.productImages.length - 1) {
      const temp = this.form.productImages[index];
      this.$set(this.form.productImages, index, this.form.productImages[index + 1]);
      this.$set(this.form.productImages, index + 1, temp);
    }
  },
    getBrandType(){
      this.$httpApi("/api/brands", {
      }, 'get').then(res => {
        this.brandOptions = res.data;
      })
    },
    editProductFunc(item){
      this.$httpApi("/api/proInfo", {
        id: item.id,
        token: this.userInfo.token,
      }).then(res => {
        res.data.brand = res.data.brand_id;
        res.data.productType = res.data.catid;
        let temp = res.data.thumb.split(',');
        console.log(temp,'dedee')
        res.data.productImages = [];
        temp.map(item => {
          res.data.productImages.push({
            url: item,
            file_path: item,
            name: item,
            id:item,
          })
        })

        res.data.certificatesAndMaterials = [];
        res.data.imgs.map(item => {
          res.data.certificatesAndMaterials.push({
            url: item,
            file_path: item,
            name: item,
            id:item,
          })
        })
        this.form = res.data;
        this.form.id= item.id;
      })
      
    },
    getType() {
      this.$httpApi("/api/channelList", {
      }, 'get').then(res => {
        this.typeOptions = res.data;
      })
    },
    handleProductImageSuccess(response, file, fileList) {
      file.file_path = response.data.path;
      this.form.productImages = fileList;
    },
    handleRemoveProductImage(file, fileList) {
      this.form.productImages = fileList;
      console.log('产品图片移除成功', this.form.productImages, fileList)
    },
    handleProductImageError(err, file, fileList) {
      console.log('产品图片上传失败', err, file, fileList);
    },
    beforeProductImageUpload(file) {
      if (file.size / 1024 / 1024 > 10) {
        this.$message.error('图片大小不能超过10M');
        return false;
      }
      return true;
    },
    handleCertificateSuccess(response, file, fileList) {
      file.file_path = response.data.path;
      this.form.certificatesAndMaterials = fileList;
    },
    handleCertificateError(err, file, fileList) {
      console.log('证书及产品资料上传失败', err, file, fileList);
      alertErr(err);
    },
    handleRemoveCertificate(file, fileList) {
      this.form.certificatesAndMaterials = fileList;
    },
    beforeCertificateUpload(file) {
      if (file.size / 1024 / 1024 > 10) {
        this.$message.error('图片大小不能超过10M');
        return false;
      }
      return true;
    },
    cancel() {
      this.$emit('cancel');
    },
    submitForm() {
      console.log('触发提交操作', this.form);
      // 这里添加将表单数据发送到后端的逻辑
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let imgs = [];
          this.form.productImages.map(item => {
            imgs.push(item.file_path);
          });
          let thumb = [];
          this.form.certificatesAndMaterials.map(item => {
            thumb.push(item.file_path);
          });
          this.$httpApi("/api/proAdd", {
            id: this.form.id ? this.form.id : undefined,
            token: this.userInfo.token,
            title: this.form.title,
            brand_id: this.form.brand,
            catid: this.form.productType,
            price: this.form.price,
            content: this.form.content,
            thumb: imgs.join(','),
            imgs: thumb.join(','),
            sort: this.form.sort,
          }, 'post').then(res => {
            if (res.code == 200) {
              alertSucc('保存成功');
              this.form = {
                productImages: [],
                title: '',
                brand: '',
                productType: '',
                price: '',
                content: '',
                certificatesAndMaterials: []
              };
            } else {
              alertErr(res.msg)
            }
          }).catch(err => {
            alertErr(err)
          })
        }
      });

    }
  }
}
</script>

<style lang="less" scoped>
/* 其他样式保持不变 */
/deep/ .quill-editor-custom .ql-container {
  height: 200px; /* 设置编辑器高度 */
}
.upText {

  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #A2A2A2;

  font-style: normal;
  text-transform: none;
}

.upBtn {
  width: 100px;
  height: 36px;
  background: #46A0FC;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid rgba(0, 0, 0, 0);
  line-height: 36px;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #FFFFFF;
  text-align: center;
  font-style: normal;
  text-transform: none;
  margin: auto;
}



.btnPay {
  width: 133px;
  height: 40px;
  background: #0052D9;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid rgba(0, 0, 0, 0);
  margin-top: 10px;
  font-family: Microsoft YaHei, Microsoft YaHei;
  font-weight: 400;
  font-size: 14px;
  color: #FFFFFF;

  font-style: normal;
  text-transform: none;
}

.btnColse {
  width: 133px;
  height: 40px;
  background: #F5F5F5;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #D7D7D7;

  font-family: Microsoft YaHei, Microsoft YaHei;
  font-weight: 400;
  font-size: 14px;
  color: #666666;


  font-style: normal;
  text-transform: none;
}

/deep/ .el-textarea__inner {
  width: 930px;
  background: #FAFAFA;
  border-radius: 4px 4px 4px 4px;
}

/deep/ .el-input__inner {
  background: #FAFAFA;
  border-radius: 4px 4px 4px 4px;
}

.formBd {
  margin-top: 28px;
}

.priceWidth {
  width: 309px;

}

.inputWidth {
  width: 680px;

}

.textareaWidth {
  width: 680px;

}

.uploadImg {
  width: 680px;
  height: 202px;
  background: #F8F8F8;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #EBEBEB;
}

.upload-tip {

  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #999999;
  line-height: 24px;
  text-align: left;
  font-style: normal;
  text-transform: none;
  margin-top: 8px;
}

.image-actions {
  position: relative;
  width: 100%;
  height: 100%;
  
  .action-buttons {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex; /* Ensure buttons are always visible */
    gap: 10px;
    z-index: 10; /* Ensure buttons are above the image */
  }
}


</style>